﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    public class DS_csv : IDS
    {
        public override void Create(MyList a)
        {
            using (StreamWriter sw = File.AppendText(path))
            {
                foreach (Person pp in a)
                {
                    sw.WriteLine(pp.SaveToSCV());
                }
                sw.Close();
            }
        }
        public override IDS IsReady(string Fname)
        {
            
            path = Fname;
            IDS ret = new DS_csv();
            string[] ext = path.Split('.');
            if (ext[1] == "csv")
            {
                ret = this;
            }
            else
            {
                if (!(next == null)) ret = next.IsReady(Fname);
            }
            return ret;
        }
        public override MyList Read()
        {
            MyList a = new MyList();
            using (StreamReader sr = File.OpenText(path))
            {
                string str;
                while ((str = sr.ReadLine()) != null)
                {
                    string[] split = str.Split(new Char[] { ';' });
                    Person type = new Person();
                    type.LoadFromCSV(split);
                    a.Add(type);
                }
                sr.Close();
                return a;
            }
        }
        public override void Update(int id, string fname, string lname, int age) 
        {
            MyList a = new MyList();
            a = Read(); 
            foreach (Person p in a) 
            {
                if (p.id == id) 
                {
                    p.FName = fname;
                    p.LName = lname;
                    p.Age = age;
                }
            }
            replace(a);
          
        }
        void replace(MyList a)
        {
            
        }
        public override void Delete(int id)
        {
        
            MyList a = new MyList();
            using (StreamReader sr = File.OpenText(path))
            {
                using (StreamWriter sw = File.CreateText(@"temp.txt"))
                {
                string str;
                while ((str = sr.ReadLine()) != null)
                {
                    string[] split = str.Split(new Char[] { ';' });                   
                    if (Convert.ToInt32(split[1]) != id)
                    {
                        sw.WriteLine(str);
                    }

                }
                sw.Close();
                }
                sr.Close();               
            }
            File.Replace(path, @"temp.txt", @"BackUp.txt");
        }       
    }
}
